<template>
  <div class="terminal-panel">
    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-tag :type="connected ? 'success' : connecting ? 'warning' : 'info'">
          {{ connected ? '已连接' : connecting ? '连接中...' : '准备连接' }}
        </el-tag>
        <span class="server-info">{{ serverName }}</span>
      </div>
      <div class="toolbar-right">
        <el-button v-if="connected" type="danger" size="small" @click="disconnect">
          断开
        </el-button>
        <el-button v-else-if="!connecting" type="primary" size="small" @click="connect">
          重新连接
        </el-button>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-area">
      <!-- 侧边监控面板 -->
      <div v-if="connected" class="monitor-panel">
        <div class="panel-header">
          <h3>服务器监控</h3>
          <el-button
            size="small"
            :icon="Refresh"
            circle
            @click="refreshMonitoring"
          />
        </div>

        <div class="monitor-content">
          <div v-if="monitoring" class="monitor-items">
            <!-- CPU -->
            <div class="monitor-item">
              <div class="item-header">
                <span class="item-label">CPU使用率</span>
                <span class="item-value">{{ monitoring.cpu }}%</span>
              </div>
              <el-progress :percentage="monitoring.cpu" :color="getColor(monitoring.cpu)" />
            </div>

            <!-- 内存 -->
            <div class="monitor-item">
              <div class="item-header">
                <span class="item-label">内存使用率</span>
                <span class="item-value">{{ monitoring.memory }}%</span>
              </div>
              <el-progress
                :percentage="monitoring.memory"
                :color="getColor(monitoring.memory)"
              />
            </div>

            <!-- 硬盘 -->
            <div class="monitor-item">
              <div class="item-header">
                <span class="item-label">硬盘使用</span>
                <span class="item-value">{{ monitoring.disk }}</span>
              </div>
              <el-progress
                :percentage="parseFloat(monitoring.disk)"
                :color="getColor(parseFloat(monitoring.disk))"
              />
            </div>

            <!-- 运行时间 -->
            <div class="monitor-item">
              <div class="item-header">
                <span class="item-label">运行时间</span>
              </div>
              <div class="item-text">{{ monitoring.uptime }}</div>
            </div>
          </div>

          <div v-else class="monitor-loading">
            <el-icon class="is-loading"><Loading /></el-icon>
            <span>加载监控数据...</span>
          </div>
        </div>
      </div>

      <!-- 终端区域 -->
      <div class="terminal-area">
        <div ref="terminalRef" class="terminal"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { getServerById } from '@/api/servers'
import { Terminal } from 'xterm'
import { FitAddon } from 'xterm-addon-fit'
import { WebLinksAddon } from 'xterm-addon-web-links'
import 'xterm/css/xterm.css'
import { ElMessage } from 'element-plus'
import { Refresh, Loading } from '@element-plus/icons-vue'

const props = defineProps({
  serverId: {
    type: Number,
    required: true
  },
  serverName: {
    type: String,
    required: true
  },
  isActive: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['close'])

const connected = ref(false)
const connecting = ref(false)
const terminalRef = ref(null)
const monitoring = ref(null)

let terminal = null
let fitAddon = null
let ws = null

// 初始化终端
const initTerminal = () => {
  if (terminal) return
  
  terminal = new Terminal({
    cursorBlink: true,
    fontSize: 14,
    fontFamily: 'Menlo, Monaco, "Courier New", monospace',
    theme: {
      background: '#1e1e1e',
      foreground: '#cccccc',
      cursor: '#ffffff',
      selection: 'rgba(255, 255, 255, 0.3)'
    },
    rows: 30,
    cols: 100
  })

  fitAddon = new FitAddon()
  terminal.loadAddon(fitAddon)
  terminal.loadAddon(new WebLinksAddon())

  terminal.open(terminalRef.value)
  fitAddon.fit()

  // 窗口大小调整
  const resizeHandler = () => {
    if (fitAddon) {
      fitAddon.fit()
    }
  }
  window.addEventListener('resize', resizeHandler)

  console.log('✅ 终端初始化成功')
}

// 连接服务器
const connect = async () => {
  if (connecting.value || connected.value) {
    return
  }
  
  try {
    connecting.value = true
    console.log('🔌 开始连接SSH...')
    const token = localStorage.getItem('token')
    
    // 建立WebSocket连接
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
    const wsUrl = `${protocol}//${window.location.host}/ws/ssh?token=${token}&serverId=${props.serverId}`
    
    ws = new WebSocket(wsUrl)

    ws.onopen = () => {
      console.log('✅ WebSocket连接成功')
      terminal.writeln('\x1b[32m正在连接服务器...\x1b[0m')
      connecting.value = false
    }

    ws.onmessage = (event) => {
      const message = JSON.parse(event.data)
      
      switch (message.type) {
        case 'status':
          terminal.writeln(`\x1b[33m${message.message}\x1b[0m`)
          break

        case 'connected':
          terminal.writeln(`\x1b[32m${message.message}\x1b[0m`)
          connected.value = true
          startMonitoring()
          break

        case 'data':
          terminal.write(message.data)
          break

        case 'monitoring':
          monitoring.value = message.data
          break

        case 'error':
          terminal.writeln(`\x1b[31m错误: ${message.message || message.data}\x1b[0m`)
          break

        case 'disconnected':
          terminal.writeln(`\x1b[31m${message.message}\x1b[0m`)
          connected.value = false
          stopMonitoring()
          break

        default:
          console.warn('未知消息类型:', message.type)
      }
    }

    ws.onerror = (error) => {
      console.error('❌ WebSocket错误:', error)
      ElMessage.error('连接失败')
      terminal.writeln('\x1b[31m连接失败\x1b[0m')
      connecting.value = false
    }

    ws.onclose = () => {
      console.log('🔌 WebSocket连接关闭')
      connected.value = false
      connecting.value = false
      stopMonitoring()
    }

    // 监听终端输入
    terminal.onData((data) => {
      if (ws && ws.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify({
          type: 'input',
          data
        }))
      }
    })

  } catch (error) {
    console.error('❌ 连接失败:', error)
    ElMessage.error('连接失败')
    connecting.value = false
  }
}

// 断开连接
const disconnect = () => {
  if (ws) {
    ws.close()
    ws = null
  }
  stopMonitoring()
  connected.value = false
  console.log('🔌 已断开连接')
}

// 开始监控
const startMonitoring = () => {
  if (ws && ws.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify({ type: 'start_monitor' }))
    console.log('📊 开始监控')
  }
}

// 停止监控
const stopMonitoring = () => {
  if (ws && ws.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify({ type: 'stop_monitor' }))
  }
}

// 刷新监控数据
const refreshMonitoring = () => {
  if (ws && ws.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify({ type: 'monitor' }))
    console.log('🔄 刷新监控数据')
  }
}

// 获取进度条颜色
const getColor = (percentage) => {
  if (percentage < 60) return '#67c23a'
  if (percentage < 80) return '#e6a23c'
  return '#f56c6c'
}

// 监听标签页激活状态，重新调整终端大小
watch(() => props.isActive, (isActive) => {
  if (isActive && fitAddon) {
    setTimeout(() => {
      fitAddon.fit()
    }, 100)
  }
})

onMounted(() => {
  console.log('📺 终端面板加载:', props.serverName)
  initTerminal()
  
  // 自动连接
  setTimeout(() => {
    connect()
  }, 500)
})

onUnmounted(() => {
  console.log('📺 终端面板卸载:', props.serverName)
  disconnect()
  if (terminal) {
    terminal.dispose()
  }
})
</script>

<style scoped>
.terminal-panel {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  background: #1e1e1e;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background: #2d2d2d;
  border-bottom: 1px solid #3e3e3e;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.server-info {
  font-size: 14px;
  color: #ccc;
}

.main-area {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.monitor-panel {
  width: 280px;
  background: #252525;
  border-right: 1px solid #3e3e3e;
  display: flex;
  flex-direction: column;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #3e3e3e;
}

.panel-header h3 {
  font-size: 14px;
  font-weight: 600;
  color: #fff;
  margin: 0;
}

.monitor-content {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
}

.monitor-items {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.monitor-item {
  padding: 15px;
  background: #2d2d2d;
  border-radius: 8px;
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.item-label {
  font-size: 12px;
  color: #999;
}

.item-value {
  font-size: 14px;
  font-weight: 600;
  color: #fff;
}

.item-text {
  font-size: 13px;
  color: #ccc;
}

.monitor-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #666;
  gap: 10px;
}

.terminal-area {
  flex: 1;
  overflow: hidden;
}

.terminal {
  width: 100%;
  height: 100%;
  padding: 10px;
}
</style>

